<template>
  <div class="row mt-3">
    <div class="col-md-12 col-lg-12">
      <div class="card">
        <div class="card-bod">
          <img src="../assets/2.jpg" alt class="mx-auto d-block" />
          <form @submit.prevent="onSubimt">
            <div class="form-group">
              <label for="email">邮箱</label>
              <input type="email" class="form-control" v-model="email" />
            </div>
            <div class="form-group">
              <label for="password">密码</label>
              <input type="password" class="form-control" v-model="password" />
            </div>
            <button class="btn btn-block btn-success" type="submit">登录</button>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      email: "",
      password: ""
    };
  },
  //组件内得守卫
  beforeRouteEnter(to, from, next) {
    next(vm => vm.$store.dispatch("setUser", null));
  },
  methods: {
    onSubimt() {
      // console.log(123)
      axios.get("/users.json").then(res => {
        //console.log(res)
        const data = res.data;
        const users = [];
        for (let key in data) {
          const user = data[key];
          users.push(user);
        }
        //console.log(users);
        //过滤数据
        let result = users.filter(user => {
          return user.email === this.email && user.password === this.password;
        });
        //判断result是否存在
        if (result != null && result.length > 0) {
          this.$store.dispatch("setUser", result[0].email);
          this.$router.push("Home");
        } else {
          alert("账号密码错了");
          this.$store.dispatch("setUser", null);
        }
      });
    }
  }
};
</script>

<style  scoped>
</style>
